<template>
	<!-- 留言板 -->
	<div>
		<!-- 留言框:内容长度10字之内 -->
		<el-input
			@keyup.native.13="submit"
			v-model.trim="content"
			type="textarea"
			v-bind:maxlength="maxlength"
			show-word-limit
			placeholder="留言信息"
		></el-input>
		<!-- 按钮:判断不许为空,长度不超过10个 -->
		<el-row :gutter="10" style="margin-top: 10px">
			<el-col :offset="22" :span="2">
				<el-button @click="submit" type="primary">提交</el-button>
			</el-col>
		</el-row>
		<!-- 展示列表:请求回来的数据 -->
		<el-card :key="item.id" v-for="item in words">
			<div slot="header">
				<el-row :gutter="10">
					<!-- 头像 -->
					<el-col :span="2">
						<el-avatar :size="50" :src="item.headIoc"></el-avatar>
					</el-col>

					<el-col :span="6">
						<!-- 昵称 -->
						<h4>{{ item.name }}</h4>
						<!-- 时间 -->
						<p>{{ item.date }}</p>
					</el-col>
				</el-row>
			</div>
			<div class="card-body">
				<!-- 留言的内容 -->
				<h5 v-html="item.content"></h5>
			</div>
		</el-card>
	</div>
</template>

<script>
export default {
	mounted() {},
	data() {
		return {
			maxlength: 20,
			// 输入框的文本
			content: '',
			// 留言的数据集合
			words: [],
		}
	},
	methods: {
		// 提交留言
		submit() {
			// 1. 校验--不许为空,不许超过10个字符
			if (this.content.length > this.maxlength || !this.content) {
				return this.$message({
					message: '抱歉,您不能提交',
					type: 'error',
				})
			}
			// 2. 假装-ajax请求提交数据
			const date = this.fromatdate()
			this.words.unshift({
				id: date,
				date,
				name: '小王',
				content: this.content,
				headIoc:
					'',
			})
			this.content = ''
			// 3. 接口如果返回成功,再次请求获取留言数据的接口
			this.getWords()
		},
		// 请求留言数据
		getWords() {
			// ajax获取留言数据
		},
		// 获取格式化后的当前时间
		fromatdate() {
			const day = new Date()
			const Y = day.getFullYear()
			const M = day.getMonth() + 1
			const d = day.getDate()
			const h = day.getHours()
			const m = day.getMinutes()
			const s = day.getSeconds()
			return `${Y}-${M}-${d} ${h}:${m}:${s}`
		},
	},
	watch: {
		content(value) {
			if (value.trim().length >= this.maxlength) {
				this.$message({
					message: `您已输入到最大长度${this.maxlength}位字符`,
					showClose: true,
					type: 'waning',
				})
			}
		},
	},
}
</script>
